package com.demo.practiceui.views.interactive;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

/**
 * 倒计时控件
 * 核心知识点：
 * 1. CountDownTimer - 倒计时工具类
 * 2. drawText - 绘制文字
 * 3. drawArc - 绘制倒计时圆环
 * 4. 时间格式化
 */
public class CountDownView extends View {

    // 倒计时参数
    private long totalTime = 60000;     // 总时间（毫秒）
    private long remainingTime = 60000; // 剩余时间（毫秒）
    private boolean isRunning = false;

    // 画笔
    private Paint bgArcPaint;       // 背景圆弧画笔
    private Paint progressArcPaint; // 进度圆弧画笔
    private Paint timePaint;        // 时间文字画笔
    private Paint labelPaint;       // 标签文字画笔

    // 尺寸
    private int width;
    private int height;
    private float centerX;
    private float centerY;
    private float radius;
    private float strokeWidth = 25f;

    private RectF rectF;
    private CountDownTimer countDownTimer;

    public CountDownView(Context context) {
        this(context, null);
    }

    public CountDownView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CountDownView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        // 背景圆弧画笔
        bgArcPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        bgArcPaint.setColor(Color.parseColor("#E0E0E0"));
        bgArcPaint.setStyle(Paint.Style.STROKE);
        bgArcPaint.setStrokeWidth(strokeWidth);
        bgArcPaint.setStrokeCap(Paint.Cap.ROUND);

        // 进度圆弧画笔
        progressArcPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        progressArcPaint.setColor(Color.parseColor("#FF5722"));
        progressArcPaint.setStyle(Paint.Style.STROKE);
        progressArcPaint.setStrokeWidth(strokeWidth);
        progressArcPaint.setStrokeCap(Paint.Cap.ROUND);

        // 时间文字画笔
        timePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        timePaint.setColor(Color.parseColor("#333333"));
        timePaint.setTextSize(72f);
        timePaint.setTextAlign(Paint.Align.CENTER);
        timePaint.setFakeBoldText(true);

        // 标签文字画笔
        labelPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        labelPaint.setColor(Color.parseColor("#999999"));
        labelPaint.setTextSize(32f);
        labelPaint.setTextAlign(Paint.Align.CENTER);

        rectF = new RectF();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        if (widthMode == MeasureSpec.AT_MOST) {
            width = 400;
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            height = 400;
        }
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
        centerX = width / 2f;
        centerY = height / 2f;
        radius = Math.min(width, height) / 2f - strokeWidth - 30;

        rectF.set(centerX - radius, centerY - radius,
                centerX + radius, centerY + radius);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 1. 绘制背景圆环
        canvas.drawCircle(centerX, centerY, radius, bgArcPaint);

        // 2. 绘制进度圆弧
        float progress = (float) remainingTime / totalTime;
        float sweepAngle = 360f * progress;
        
        // 根据剩余时间改变颜色
        if (progress > 0.5f) {
            progressArcPaint.setColor(Color.parseColor("#4CAF50"));  // 绿色
        } else if (progress > 0.2f) {
            progressArcPaint.setColor(Color.parseColor("#FFC107"));  // 黄色
        } else {
            progressArcPaint.setColor(Color.parseColor("#FF5722"));  // 红色
        }
        
        canvas.drawArc(rectF, -90, sweepAngle, false, progressArcPaint);

        // 3. 绘制时间文字
        String timeText = formatTime(remainingTime);
        canvas.drawText(timeText, centerX, centerY + 25, timePaint);

        // 4. 绘制标签
        String label = isRunning ? "剩余时间" : "点击开始";
        canvas.drawText(label, centerX, centerY + 70, labelPaint);
    }

    /**
     * 格式化时间（毫秒转为 MM:SS 格式）
     */
    private String formatTime(long millis) {
        long seconds = millis / 1000;
        long minutes = seconds / 60;
        seconds = seconds % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }

    /**
     * 开始倒计时
     */
    public void start() {
        if (isRunning) {
            return;
        }

        isRunning = true;
        
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }

        countDownTimer = new CountDownTimer(remainingTime, 50) {
            @Override
            public void onTick(long millisUntilFinished) {
                remainingTime = millisUntilFinished;
                invalidate();
            }

            @Override
            public void onFinish() {
                remainingTime = 0;
                isRunning = false;
                invalidate();
                
                // 倒计时结束，可以添加回调
                if (onCountDownListener != null) {
                    onCountDownListener.onFinish();
                }
            }
        };
        
        countDownTimer.start();
    }

    /**
     * 暂停倒计时
     */
    public void pause() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        isRunning = false;
        invalidate();
    }

    /**
     * 重置倒计时
     */
    public void reset() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        isRunning = false;
        remainingTime = totalTime;
        invalidate();
    }

    /**
     * 设置总时间（秒）
     */
    public void setTotalTime(int seconds) {
        this.totalTime = seconds * 1000L;
        this.remainingTime = this.totalTime;
        invalidate();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    // 回调接口
    private OnCountDownListener onCountDownListener;

    public interface OnCountDownListener {
        void onFinish();
    }

    public void setOnCountDownListener(OnCountDownListener listener) {
        this.onCountDownListener = listener;
    }
}

